package me.zhengjie.utils;

import cn.hutool.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;


public class HttpUtil {

    /**
     * 发送POST请求
     *
     * @param url 请求的URL
     * @param object 请求体对象
     * @return 响应字符串
     */
    public static String sendPost(String url, Object object) throws IOException {
        // 将请求对象转换为JSON字符串
        String jsonInputString = new JSONObject(object).toString();

        StringBuilder result = new StringBuilder();
        try {
            // 创建URL对象
            URL obj = new URL(url);
            // 打开连接
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            // 设置请求方法
            con.setRequestMethod("POST");
            // 设置请求头
            con.setRequestProperty("Content-Type", "application/json; utf-8");
            con.setRequestProperty("Accept", "application/json");
            // 发送POST请求必须设置这个
            con.setDoOutput(true);

            // 获取输出流，并写入参数
            try(OutputStream os = con.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应码
            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                try(BufferedReader in = new BufferedReader(
                        new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        result.append(inputLine);
                    }
                }
            } else {
                System.out.println("POST请求返回非200了：" + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

}